package chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.UnsupportedEncodingException;
import java.util.Scanner;

/**
 * @Author 刘牌
 * @Date 2020/3/16 0016 16:17
 * @Version 1.0
 */

public class NettyEchoClient {
    private int serverPort;
    private String serverIp;

    public NettyEchoClient(int serverPort, String serverIp) {
        this.serverPort = serverPort;
        this.serverIp = serverIp;
    }
    Bootstrap b = new Bootstrap();

    public void runClient() throws InterruptedException, UnsupportedEncodingException {
        EventLoopGroup workGroup = new NioEventLoopGroup();
        b.group(workGroup)
                .channel(NioSocketChannel.class)
                .remoteAddress(serverIp,serverPort)
                .option(ChannelOption.ALLOCATOR , PooledByteBufAllocator.DEFAULT)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new NettyClientHandler());
                    }
                });
        ChannelFuture connect = b.connect();
        connect.addListener((ChannelFuture futureListener) ->{
            if (futureListener.isSuccess()){
                System.out.println("客户端连接成功");
            }
            else {
                System.out.println("客户端连接失败");
            }
        });
        connect.sync();
        Channel channel = connect.channel();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入内容---------");
        while (scanner.hasNext()){
            String next = scanner.next();
            byte[] bytes = next.getBytes("UTF-8");
            ByteBuf buffer = channel.alloc().buffer();
            buffer.writeBytes(bytes);
            channel.writeAndFlush(buffer);
            System.out.println("请输入发送内容");
        }
        workGroup.shutdownGracefully();
    }

    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
        new NettyEchoClient(7001,"127.0.0.1").runClient();
    }
}
